package com.blm.service.impl;

import com.blm.common.constants.CacheConstant;
import com.blm.common.constants.ExceptionConstant;
import com.blm.entity.Favorite;
import com.blm.entity.Food;
import com.blm.entity.Store;
import com.blm.exception.CommonException;
import com.blm.repository.FavoriteRepository;
import com.blm.repository.FoodRepository;
import com.blm.service.FavoriteService;
import com.blm.service.StoreService;
import com.blm.util.RedisUtil;
import com.blm.vo.FoodVO;
import com.blm.vo.PageVO;
import com.blm.vo.StoreVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FavoriteServiceImpl implements FavoriteService {

    @Autowired
    private FavoriteRepository favoriteRepository;

    @Autowired
    private FoodRepository foodRepository;

    @Autowired @Lazy
    private FavoriteService self;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private StoreService storeService;

    @Override
    @Cacheable(value = CacheConstant.FAV_STORE, key = "#userId + '_' + #page + '_' + #size")
    public PageVO<StoreVO> listFavoriteStores(Long userId, int page, int size) {
        PageHelper.startPage(page, size);

        List<Favorite> favStores = favoriteRepository.findAllByUserId(userId, Favorite.TYPE_STORE);
        Page<Favorite> pageInfo = (Page<Favorite>) favStores;

        List<StoreVO> storeVOs = favStores.stream().map(fav -> {
            Store store = storeService.getStoreById(fav.getTargetId());
            StoreVO vo = new StoreVO();
            BeanUtils.copyProperties(store, vo);
            return vo;
        }).collect(Collectors.toList());

        return new PageVO<>(page, size, pageInfo.getTotal(), pageInfo.getPages(), storeVOs);
    }

    @Override
    @Transactional
    @CachePut(value = CacheConstant.FAV_QUERY, key = "#userId + '_STORE_' + #storeId")
    public Integer addStoreFavorite(Long userId, Long storeId) {
        int count = self.queryFavorite(userId, storeId, Favorite.TYPE_STORE);
        if (count > 0) {
            throw new CommonException(ExceptionConstant.STORE_ALREADY_FAV);
        }
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setTargetId(storeId);
        favorite.setType(Favorite.TYPE_STORE);
        favorite.setCreatedAt(LocalDateTime.now());
        favoriteRepository.insert(favorite);
        redisUtil.clearCache(CacheConstant.FAV_STORE, userId);

        return 1;
    }

    @Override
    @Transactional
    @CachePut(value = CacheConstant.FAV_QUERY, key = "#userId + '_STORE_' + #storeId")
    public Integer removeStoreFavorite(Long userId, Long storeId) {
        favoriteRepository.deleteByUserIdAndTargetId(userId, storeId, Favorite.TYPE_STORE);
        redisUtil.clearCache(CacheConstant.FAV_STORE, userId);
        return 0;
    }
    
    @Override
    @Cacheable(value = CacheConstant.FAV_FOOD, key = "#userId + '_' + #page + '_' + #size")
    public PageVO<FoodVO> listFavoriteFoods(Long userId, int page, int size) {
        PageHelper.startPage(page, size);

        List<Favorite> favFoods = favoriteRepository.findAllByUserId(userId, Favorite.TYPE_FOOD);
        Page<Favorite> pageInfo = (Page<Favorite>) favFoods;

        List<FoodVO> foodVOs = favFoods.stream().map(fav -> {
            Food food = foodRepository.findById(fav.getTargetId())
                    .orElseThrow(() -> new CommonException(ExceptionConstant.FOOD_NOT_FOUND));
            FoodVO vo = new FoodVO();
            BeanUtils.copyProperties(food, vo);
            return vo;
        }).collect(Collectors.toList());

        return new PageVO<>(page, size, pageInfo.getTotal(), pageInfo.getPages(), foodVOs);
    }
    
    @Override
    @Transactional
    @CachePut(value = CacheConstant.FAV_QUERY, key = "#userId + '_FOOD_' + #foodId")
    public Integer addFoodFavorite(Long userId, Long foodId) {
        int count = self.queryFavorite(userId, foodId, Favorite.TYPE_FOOD);
        if (count > 0) {
            throw new CommonException(ExceptionConstant.FOOD_ALREADY_FAV);
        }
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setTargetId(foodId);
        favorite.setType(Favorite.TYPE_FOOD); // 添加类型标识
        favorite.setCreatedAt(LocalDateTime.now());
        favoriteRepository.insert(favorite);
        redisUtil.clearCache(CacheConstant.FAV_FOOD, userId);

        return 1;
    }
    
    @Override
    @Transactional
    @CachePut(value = CacheConstant.FAV_QUERY, key = "#userId + '_FOOD_' + #foodId")
    public Integer removeFoodFavorite(Long userId, Long foodId) {
        favoriteRepository.deleteByUserIdAndTargetId(userId, foodId, Favorite.TYPE_FOOD);
        redisUtil.clearCache(CacheConstant.FAV_FOOD, userId);
        return 0;
    }

    @Override
    @Cacheable(value = CacheConstant.FAV_QUERY, key = "#userId + '_' + #targetType + '_' + #targetId")
    public Integer queryFavorite(Long userId, Long targetId, String targetType) {
        return favoriteRepository.countByUserIdAndTargetId(userId, targetId, targetType);
    }
}